package NewChatRoom;

import javax.swing.*;
import java.io.*;
import java.net.Socket;

public class serverHandlerThread extends Thread{
    private Socket client;
    private DataOutputStream dos;
    private UserInfo userInfo;
    ResultToServer rs = new ResultToServer();

    public void run(){
        processHandler();
    }
    public serverHandlerThread(Socket client){
        this.client = client;
    }
    //获取线程处理的用户
    public UserInfo getOwnUser(){
        return this.userInfo;
    }
    public void sendMsgToClient(String msg){
        try {
            msg+="\n";
            dos.writeUTF(msg);
            dos.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void processHandler(){
        try {
            InputStream is = client.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            dos = new DataOutputStream(client.getOutputStream());
            sendMsgToClient("欢迎来到聊天室！请登录，输入用户名：");
            String username = dis.readUTF();
            sendMsgToClient("请输入密码：");
            String psw = dis.readUTF();
            userInfo = new UserInfo();
            userInfo.setName(username);
            userInfo.setPassword(psw);
            //验证用户是否存在
            AccountDAO dao = new AccountDAO();
            int result = dao.searchName(username);
            boolean canLogin = false;
            if(result!=0){
                if(psw.equals(dao.get(result).getPsw())){
                    //System.out.println("登录成功");
                    rs.print(username+"登录成功" + "\n");
                    dos.writeUTF("登录成功");
                    dos.flush();
                    canLogin = true;
                }else {
                    //System.out.println("密码错误");
                    dos.writeUTF("密码错误");
                    dos.flush();
                }
            }else{
                //System.out.println("账号不存在");
                dos.writeUTF("账号不存在");
                dos.flush();
            }


            if(canLogin==false){
                //账号验证失败，关闭线程
                this.closeMe();
                return;
            }
            ChatThreadManager.addClient(this);

            String input;

            //循环监听
            while (!client.isClosed()){
                //System.out.println("服务器收到的是"+input);
                input = dis.readUTF();//读取下一条
                rs.print(username+"说:"+input+"\n");
                ChatThreadManager.castMsg(this.userInfo,input);

            }
        }catch (IOException e){
            e.printStackTrace();
        }
        //收到bye后停止循环
        ChatThreadManager.ClientExit(this.userInfo);
        SwingUtilities.updateComponentTreeUI(ServerGUI.table_online);
    }
    public void closeMe(){
        try {
            client.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
